package com.cloud.bssp.juc.reetrantlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description： 定时测试
 * @author：weirx
 * @date：2021/12/13 15:46
 * @version：3.0
 */
public class TryLockTimeTest {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            try {
                if (!lock.tryLock(1, TimeUnit.SECONDS)) {
                    System.out.println("等待一秒获取锁失败");
                    return;
                } else {
                    try {
                        System.out.println("等待一秒获取锁成功");
                    } finally {
                        lock.unlock();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        lock.lock();
        try {
            t1.start();
            System.out.println("等待两秒");
            TimeUnit.SECONDS.sleep(2);
        } finally {
            lock.unlock();
        }
    }
}
